package com.zjp.shiro.config;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zjp.shiro.mapper.UserMapper;
import com.zjp.shiro.pojo.User;

@Component
public class MyShiroRealm extends AuthorizingRealm {
	
	Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);
	
	@Autowired
	UserMapper userMapper;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		
		
		logger.info("用户权限验证");
		String username = (String) principalCollection.getPrimaryPrincipal();
		if("zhangjiapeng".endsWith(username)){
			SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
			Set<String> permissionSet = new HashSet<String>();
			permissionSet.add("add");
			info.setStringPermissions(permissionSet);
		    return info;
		}
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		logger.info("用户身份验证");
		UsernamePasswordToken authToken = (UsernamePasswordToken) token;
		String username = (String) authToken.getUsername();
		
		User user = userMapper.queryUserByName(username);
		if(user == null){
			throw new AccountException("帐号或密码不正确！");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,user.getAge()+"",getName());
		return info;
	}

}
